<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Bed;
use app\common\model\BehaviorCategory;
use app\common\model\BehaviorRecord;
use app\common\model\BehaviorRecordDetail;
use app\common\model\BehaviorRecordImage;
use app\common\model\CommentRule;
use think\Db;
use think\Log;

/**
 * 宿舍
 *
 * package app\api\controller
 */
class Dorm extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['gardens', 'buildings', 'dorms', 'beds', 'profile', 'behaviorRecords'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiTitle    (园区列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/14)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/gardens)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="school_id", type="int", required=true, description="学校 ID", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
     * "code": 1,
     * "msg": "",
     * "time": "1581919289",
     * "data": [
     * {
     * "id": 9,
     * "number": "1001",
     * "name": "本校区"
     * }
     * ]
     * })
     */
    public function gardens()
    {
        $school_id = $this->request->request('school_id', 0);
        $list = \app\common\model\Garden::where('school_id', $school_id)
            ->field('id,number,name')
            ->select();

        $this->success('', $list);
    }

    /**
     * @ApiTitle    (楼栋列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/14)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/buildings)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="garden_id", type="int", required=true, description="园区 ID", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
     * "code": 1,
     * "msg": "",
     * "time": "1581919534",
     * "data": [
     * {
     * "id": 21,
     * "number": "1001",
     * "name": "逸夫楼",
     * "floor": 10
     * },
     * {
     * "id": 25,
     * "number": "1",
     * "name": "2",
     * "floor": 6
     * }
     * ]
     * })
     */
    public function buildings()
    {
        $garden_id = $this->request->post('garden_id', 0);

        $list = \app\common\model\Building::where('garden_id', $garden_id)
            ->whereIn('type', [2, 3])
            ->field('id,number,name,floor')
            ->select();

        if ($list) {
            $list = collection($list)->toArray();
            foreach ($list as $key => $value) {
                $list[$key]['floors'] = [];
                for ($i = 1; $i <= $value['floor']; $i++) {
                    $list[$key]['floors'][] = [
                        'id' => $i,
                        'name' => $i . '楼'
                    ];
                }
            }
        }

        $this->success('', $list);
    }

    /**
     * @ApiTitle    (宿舍列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/14)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/dorms)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="building_id", type="int", required=true, description="楼栋 ID", sample="")
     * @ApiParams   (name="floor", type="int", required=false, description="楼层", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
     * "code": 1,
     * "msg": "",
     * "time": "1581920329",
     * "data": [
     * {
     * "id": 1,
     * "number": "1-101",
     * "name": "2-101",
     * "bed_count": 8,
     * "bed_used_count": 8
     * },
     * {
     * "id": 2,
     * "number": "1-102",
     * "name": "2-102",
     * "bed_count": 8,
     * "bed_used_count": 0
     * },
     * {
     * "id": 3,
     * "number": "1-103",
     * "name": "2-103",
     * "bed_count": 8,
     * "bed_used_count": 0
     * },
     * {
     * "id": 4,
     * "number": "1-104",
     * "name": "2-104",
     * "bed_count": 8,
     * "bed_used_count": 0
     * }
     * ]
     * })
     */
    public function dorms()
    {
        $building_id = $this->request->request('building_id');
        $floor = $this->request->request('floor', 0);
        $keywords = $this->request->request('keywords', '');

        $building = \app\common\model\Building::alias('building')
            ->join('__GARDEN__ garden', 'garden.id = building.garden_id')
            ->where('building.id', $building_id)
            ->field('building.*,garden.number garden_number')
            ->find();


        if (!$building) {
            $this->success('');
        }

        $list = \app\common\model\Dorm::alias('dorm')
            ->where('dorm.school_id', $building->school_id)
            ->where('dorm.garden_number', $building->garden_number)
            ->where('dorm.building_number', $building->number)
            ->where(function ($query) use ($floor, $keywords) {
                if ($floor) {
                    $query->where('dorm.floor', $floor);
                }
                if ($keywords) {
                    $query->whereLike('dorm.number', "%$keywords%");
                }
            })
            ->where('dorm.status', \app\common\model\Dorm::NORMAL)
            ->field('dorm.id,dorm.number,dorm.name,dorm.bed_count,dorm.bed_used_count')
            ->select();

        if ($list) {
            $list = collection($list)->toArray();

            foreach ($list as $key => $value) {
                $bed_count = \app\common\model\Bed::where('school_id', $building->school_id)
                    ->where('garden_number', $building->garden_number)
                    ->where('building_number',  $building->number)
                    ->where('dorm_number', $value['number'])
                    ->where('status', \app\common\model\Bed::ZAIYONG)
                    ->count();
                $list[$key]['bed_used_count'] = $bed_count;
            }

            //当前时间段是否可以点评
//            $rule = CommentRule::checkRule(BehaviorCategory::DORM);
//            $behaviorRecords = BehaviorRecord::whereIn('behavior_category_type', [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT])
//                ->where('record_user_id', $this->auth->id)
//                ->whereIn('dorm_id', array_column($list, 'id'))
//                ->whereTime('created_at', 'today')
//                ->column('class_id');
//
//            foreach ($list as $key => $value) {
//                $ret = in_array($value['id'], $behaviorRecords);
//                $list[$key]['can_comment'] = $rule && !$ret ? true : false;
//                $list[$key]['can_edit'] = $rule && $ret ? true : (!$rule && $ret ? true : false);
//            }

            $behaviorRecords = BehaviorRecord::whereIn('behavior_category_type', [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT])
                ->where('record_user_id', $this->auth->id)
                ->whereIn('dorm_id', array_column($list, 'id'))
                ->whereTime('created_at', 'today')
                ->group('dorm_id')
                ->column('dorm_id,count(*) count');

            foreach ($list as $key => $value) {
                if (isset($behaviorRecords[$value['id']])) {
                    $list[$key]['record_count'] = $behaviorRecords[$value['id']];
                } else {
                    $list[$key]['record_count'] = 0;
                }
            }
        }

        $this->success('', $list);

    }

    /**
     * @ApiTitle    (床位列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/14)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/beds)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="dorm_id", type="int", required=true, description="宿舍 ID", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
     * "code": 1,
     * "msg": "",
     * "time": "1581920564",
     * "data": [
     * {
     * "id": 9,
     * "name": "1-10201",
     * "num": 1,
     * "status": 1
     * },
     * {
     * "id": 10,
     * "name": "1-10202",
     * "num": 2,
     * "status": 1
     * },
     * {
     * "id": 11,
     * "name": "1-10203",
     * "num": 3,
     * "status": 1
     * },
     * {
     * "id": 12,
     * "name": "1-10204",
     * "num": 4,
     * "status": 1
     * },
     * {
     * "id": 13,
     * "name": "1-10205",
     * "num": 5,
     * "status": 1
     * },
     * {
     * "id": 14,
     * "name": "1-10206",
     * "num": 6,
     * "status": 1
     * },
     * {
     * "id": 15,
     * "name": "1-10207",
     * "num": 7,
     * "status": 1
     * },
     * {
     * "id": 16,
     * "name": "1-10208",
     * "num": 8,
     * "status": 1
     * }
     * ]
     * })
     */
    public function beds()
    {
        $dorm_id = $this->request->post('dorm_id');

        $list = \app\common\model\Dorm::alias('dorm')
            ->join('__DORMITORY_DORM_BED__ bed', 'dorm.number = bed.dorm_number and dorm.garden_number = bed.garden_number and dorm.building_number = bed.building_number')
            ->where('dorm.id', $dorm_id)
            ->where('bed.status', Bed::ZAIYONG)
            ->where('dorm.status', \app\common\model\Dorm::NORMAL)
            ->field('bed.id,bed.number name,bed.num,bed.status')
            ->select();

        $this->success('', $list);

    }

    /**
     * @ApiTitle    (查看寝室信息)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/17)
     * @ApiSummary  ()
     * @ApiBody     ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/profile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="string", required=false, description="寝室 id", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
     * "code": 1,
     * "msg": "",
     * "time": "1565248066",
     * "data": {
     * "dorm": {
     * "id": 884,
     * "garden_number": "1",
     * "garden_name": "雅园",
     * "building_number": "1",
     * "building_name": "1号楼",
     * "number": "1-101"
     * },
     * "bed_list": [
     * {
     * "id": 4025,
     * "num": 1,
     * "student_id": 2
     * }
     * ]
     * }
     * })
     */
    public function profile()
    {
        $dorm_id = $this->request->post('id');
        $dorm = \app\common\model\Dorm::alias('dorm')
            ->where('dorm.id', $dorm_id)
            ->where('dorm.status', \app\common\model\Dorm::NORMAL)
            ->find();
        if (!$dorm) $this->error('寝室不存在');

        $building = \app\common\model\Building::alias('building')
            ->join('__GARDEN__ garden', 'garden.id = building.garden_id')
            ->join('__SCHOOL__ school', 'school.id = garden.school_id')
            ->where('school.id', $dorm['school_id'])
            ->where('garden.number', $dorm['garden_number'])
            ->where('building.number', $dorm['building_number'])
            ->field('school.id school_id,school.name school_name,garden.id garden_id,garden.number garden_number,garden.name garden_name,building.id building_id,building.number building_number,building.name building_name')
            ->find();

        if ($building) {
            $dorm = array_merge($dorm->toArray(), $building->toArray());
        }

        $records = BehaviorRecord::alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
            ->where('record.dorm_id', $dorm_id)
            ->where('detail.behavior_category_type', BehaviorCategory::DORM)
            ->field('SUM(CASE WHEN detail.behavior_type = 1 THEN detail.score ELSE 0 END) positive_score,ABS(SUM(CASE WHEN detail.behavior_type = 2 THEN detail.score ELSE 0 END)) negative_score')
            ->order('score', 'desc')
            ->find();

        $dorm['positive_score'] = $records->positive_score ? $records->positive_score : 0;//积极分
        $dorm['negative_score'] = $records->negative_score ? $records->negative_score : 0;//消积分

        $bed_list = Bed::where('garden_number', $dorm['garden_number'])
            ->where('building_number', $dorm['building_number'])
            ->where('dorm_number', $dorm['number'])
            ->where('status', Bed::ZAIYONG)
            ->where('student_id', '>', 0)
            ->field('id,num,number,student_id')
            ->order('num', 'asc')
            ->select();

        $data['dorm'] = $dorm;
        $data['bed_list'] = $bed_list;

        $this->success('', $data);
    }

    /**
     * @ApiTitle    (行为列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/1/17)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/classes/behaviors)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function behaviors()
    {
        $record_id = $this->request->request(('record_id'));
        $data['dorm'] = BehaviorCategory::getBehaviorData([BehaviorCategory::DORM], $record_id, $this->auth->id, $this->auth->school_id);
        $data['student'] = BehaviorCategory::getBehaviorData([BehaviorCategory::DORM_STUDENT], $record_id, $this->auth->id, $this->auth->school_id);
        $this->success('', $data);
    }

    /**
     * @ApiTitle    (点评寝室及床位)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/10)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/addBehaviorRecord)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="record_id", type="int", required=false, description="记录id 修改的时候必填", sample="")
     * @ApiParams   (name="dorm", type="json", required=true, description="寝室数据", sample="")
     * @ApiParams   (name="bed", type="json", required=true, description="床位数据", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
     * "code": 1,
     * "msg": "成功",
     * "time": "1565248642",
     * "data": null
     * })
     */
    public function addBehaviorRecord()
    {
        $record_id = $this->request->request('record_id');

        // 点评寝室数据
        $dorm_data = $this->request->post('dorm', [], 'strip_tags');
        //{"id":677,"behavior_ids":[243,246,252],"comment":"","images":""}

        // 点评床位数据
        $bed_data = $this->request->post('bed', [], 'strip_tags');
        //[{"id":3123,"comment":"","images":"","behavior_ids":[242,244,245,247,253]},{"id":3124,"comment":"","images":"","behavior_ids":[242,244,245,247,253]},{"id":3125,"comment":"","images":"","behavior_ids":[242,244,245,247,253]},{"id":3126,"comment":"","images":"","behavior_ids":[242,244,245,247,253]},{"id":3127,"comment":"","images":"","behavior_ids":[242,244,245,247,253]},{"id":3128,"comment":"","images":"","behavior_ids":[242,244,245,247,253]},{"id":3129,"comment":"","images":"","behavior_ids":[242,244,245,247,253]},{"id":3130,"comment":"","images":"","behavior_ids":[242,244,245,247,253]}]

        $behaviorRecord = [];
        if ($record_id) {
            $behaviorRecord = BehaviorRecord::where('record_user_id', $this->auth->id)->where('id', $record_id)->find();
            if (!$behaviorRecord) {
                $this->error('记录不存在');
            }
        }

        if ($dorm_data) {
            $dorm_data = json_decode($dorm_data, true);
            //$dorm_data['behavior_ids'] = array_unique($dorm_data['behavior_ids']);

            Log::info('dorm:', json_encode($dorm_data));
        }
        if ($bed_data) {
            $bed_data = json_decode($bed_data, true);
            //$bed_data['behavior_ids'] = array_unique($bed_data['behavior_ids']);

            Log::info('bed:', json_encode($bed_data));
        }

        if (!isset($dorm_data['id'])) {
            $this->error('参数错误, 请先选择要点评的寝室');
        }

        $dorm = \app\common\model\Dorm::alias('a')
            ->where('a.id', $dorm_data['id'])
            ->where('a.status', \app\common\model\Dorm::NORMAL)
            ->field('a.id,a.garden_number,a.building_number,a.name,a.number,a.school_id')
            ->find();
        if (!$dorm) {
            $this->error('您要点评的寝室不存在');
        }

        $beds = Bed::where('garden_number', $dorm['garden_number'])
            ->where('building_number', $dorm['building_number'])
            ->where('dorm_number', $dorm['number'])
            ->where('status', Bed::ZAIYONG)
            ->where('student_id', '>', 0)
            ->order('num', 'asc')
            ->column('id,num,number,student_id');

        $students = \app\common\model\Student::whereIn('id', array_column($beds, 'student_id'))->column('id,class_id');

        $dorm_detail = \app\common\model\Building::alias('building')
            ->join('__GARDEN__ garden', 'garden.id = building.garden_id')
            ->join('__SCHOOL__ school', 'school.id = garden.school_id')
            ->where('school.id', $dorm['school_id'])
            ->where('garden.number', $dorm['garden_number'])
            ->where('building.number', $dorm['building_number'])
            ->field('school.id school_id,school.name school_name,garden.id garden_id,garden.number garden_number,garden.name garden_name,building.id building_id,building.number building_number,building.name building_name')
            ->find();

        if (!$dorm_detail) {
            $this->error('error');
        }

        // 新的数组 用于存放所有的行为id
        $behavior_ids = [];

        // 判断是否有寝室点评
        if (isset($dorm_data['behavior_ids']) && $dorm_data['behavior_ids']) {
            // behavior_ids 是否是数组 不是的话转成数组(必须是以,连接)
            if (!is_array($dorm_data['behavior_ids'])) {
                $dorm_data['behavior_ids'] = explode(',', $dorm_data['behavior_ids']);
            }
            $dorm_data['behavior_ids'] = array_unique( $dorm_data['behavior_ids']);

            // 存放进behavior_ids
            $behavior_ids = $dorm_data['behavior_ids'];
        } else {
            $dorm_data['behavior_ids'] = [];
        }

        if ($bed_data) {
            foreach ($bed_data as $key => $value) {
                // 判断是否有床位点评
                if (isset($value['behavior_ids']) && $value['behavior_ids']) {
                    // behavior_ids 是否是数组 不是的话转成数组(必须是以,连接)
                    if (!is_array($value['behavior_ids'])) {
                        $bed_data[$key]['behavior_ids'] = array_unique(explode(',', $value['behavior_ids']));
                    }
                    $bed_data[$key]['behavior_ids'] = array_unique($bed_data[$key]['behavior_ids']);
                    // 把点评床位的behavior_ids 追加进$behavior_ids
                    $behavior_ids = array_merge($behavior_ids, $bed_data[$key]['behavior_ids']);
                } else {
                    $bed_data[$key]['behavior_ids'] = [];
                }
            }
        }

        // 获取并重新组合行为信息 便于下面能快速的找到指定的行为
        $behaviors = [];
        if ($behavior_ids) {
            $behavior_ids = array_unique($behavior_ids);
            $behaviors = \app\common\model\Behavior::alias('behavior')
                ->join('__BEHAVIOR_CATEGORY__ category', 'category.id = behavior.category_id')
                ->join('__BEHAVIOR_IMAGE__ image', 'image.id = behavior.image_id', 'left')
                ->whereIn('behavior.id', $behavior_ids)
                ->whereIn('category.type', [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT])
                ->column('behavior.*,category.id behavior_category_id,category.type behavior_category_type,category.is_deduct,image.url image_url');
        }

        // 当前登录用户
        $record_user_id = $this->auth->id;
        $record_user_nickname = $this->auth->nickname;
        $record_user_group = $this->auth->group_name;

        Db::startTrans();
        try {
            $insert_detail_data = [];
            $insert_image_data = [];

            if ($behaviorRecord) {
                db('behavior_record_detail')->where('record_id', $behaviorRecord->id)->delete();
                db('behavior_record_image')->where('record_id', $behaviorRecord->id)->delete();
            } else {
                // 添加事件记录
                $behaviorRecord = new BehaviorRecord();
                $behaviorRecord->data([
                    'record_user_id' => $record_user_id,
                    'record_username' => $record_user_nickname,
                    'record_user_group' => $record_user_group,
                    'behavior_category_type' => BehaviorCategory::DORM,
                    'school_id' => $dorm['school_id'],
                    'dorm_id' => $dorm['id'],
                    'comment' => isset($dorm_data['comment']) ? $dorm_data['comment'] : '',
                    'json_data' => json_encode([
                        'school_id' => $dorm_detail['school_id'],
                        'school_name' => $dorm_detail['school_name'],
                        'garden_id' => $dorm_detail['garden_id'],
                        'garden_number' => $dorm_detail['garden_number'],
                        'garden_name' => $dorm_detail['garden_name'],
                        'building_id' => $dorm_detail['building_id'],
                        'building_number' => $dorm_detail['building_number'],
                        'building_name' => $dorm_detail['building_name'],
                        'dorm_id' => $dorm['id'],
                        'dorm_number' => $dorm['number'],
                        'dorm_name' => $dorm['name'],
                    ])
                ]);
                $behaviorRecord->save();
            }

            if ($dorm_data && $dorm_data['behavior_ids']) {
                // 添加点评宿舍 detail
                foreach ($dorm_data['behavior_ids'] as $key => $value) {
                    // 查找行为
                    if (isset($behaviors[$value]) && BehaviorCategory::DORM == $behaviors[$value]['behavior_category_type']) {
                        $score = $behaviors[$value]['type'] == \app\common\model\Behavior::POSITIVE ? $behaviors[$value]['score'] : $behaviors[$value]['score'] * (-1);
                        $insert_detail_data[] = [
                            'record_id' => $behaviorRecord->id,
                            'behavior_category_id' => $behaviors[$value]['behavior_category_id'],
                            'behavior_category_type' => $behaviors[$value]['behavior_category_type'],
                            'behavior_id' => $behaviors[$value]['id'],
                            'behavior_name' => $behaviors[$value]['name'],
                            'behavior_type' => $behaviors[$value]['type'],
                            'behavior_image_id' => $behaviors[$value]['image_id'],
                            'behavior_image_url' => $behaviors[$value]['image_url'],
                            'unit_score' => $score,
                            'count' => 1,
                            'score' => $score,
                        ];
                    }
                }
                // 添加点评宿舍 image
                if (isset($dorm_data['images']) && $dorm_data['images']) {
                    $images = explode(',', $dorm_data['images']);
                    foreach ($images as $key => $value) {
                        $insert_image_data[] = [
                            'record_id' => $behaviorRecord->id,
                            'url' => $value,
                        ];
                    }
                }
            }

            // 点评床位(学生)
            if ($bed_data) {
                foreach ($bed_data as $k => $v) {
                    // 查找床位
                    if ($v['behavior_ids'] && isset($beds[$v['id']]) && isset($students[$beds[$v['id']]['student_id']])) {
                        // 添加点评床位 detail
                        foreach ($v['behavior_ids'] as $key => $value) {
                            // 查找行为
                            if (isset($behaviors[$value]) && BehaviorCategory::DORM_STUDENT == $behaviors[$value]['behavior_category_type']) {
                                $score = $behaviors[$value]['type'] == \app\common\model\Behavior::POSITIVE ? $behaviors[$value]['score'] : $behaviors[$value]['score'] * (-1);
                                $insert_detail_data[] = [
                                    'record_id' => $behaviorRecord->id,
                                    'behavior_category_id' => $behaviors[$value]['behavior_category_id'],
                                    'behavior_category_type' => $behaviors[$value]['behavior_category_type'],
                                    'behavior_id' => $behaviors[$value]['id'],
                                    'behavior_name' => $behaviors[$value]['name'],
                                    'behavior_type' => $behaviors[$value]['type'],
                                    'behavior_image_id' => $behaviors[$value]['image_id'],
                                    'behavior_image_url' => $behaviors[$value]['image_url'],
                                    'is_deduct' => $behaviors[$value]['is_deduct'],
                                    'unit_score' => $score,
                                    'count' => 1,
                                    'score' => $score,
                                    'bed_id' => $v['id'],
                                    'bed_num' => $beds[$v['id']]['num'],
                                    'student_id' => $beds[$v['id']]['student_id'],
                                    'class_id' => $students[$beds[$v['id']]['student_id']],
                                    'comment' => $v['comment'],
                                ];
                            }
                        }
                        // 添加点评床位 image
                        if (isset($v['images']) && $v['images']) {
                            $images = explode(',', $v['images']);
                            foreach ($images as $key => $value) {
                                $insert_image_data[] = [
                                    'record_id' => $behaviorRecord->id,
                                    'url' => $value,
                                    'bed_id' => $v['id'],
                                ];
                            }
                        }
                    }
                }
            }

            if (!$insert_detail_data && !$insert_image_data) {
                Db::rollback();
                $this->error('error');
            }

            // 批量保存
            if ($insert_detail_data) {
                $behaviorRecordDetail = new BehaviorRecordDetail();
                $result = $behaviorRecordDetail->saveAll($insert_detail_data);

                Log::info('insert_detail_data:' . json_encode($result));
            }
            if ($insert_image_data) {
                $behaviorRecordImage = new BehaviorRecordImage();
                $result = $behaviorRecordImage->saveAll($insert_image_data);

                Log::info('insert_detail_data:' . json_encode($result));
            }

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            $this->error($e->getMessage() ? $e->getMessage() : '失败');
        }

        $this->success('成功');

    }
//    public function addBehaviorRecord()
//    {
////        $ret = CommentRule::checkBehaviorAdd(BehaviorCategory::DORM, $this->auth->id);
////        if (isset($ret['error'])) {
////            $this->error($ret['msg']);
////        }
//
//        // 点评寝室数据
//        $dorm_data = $this->request->post('dorm', [], 'strip_tags');
//        // 点评床位数据
//        $bed_data = $this->request->post('bed', [], 'strip_tags');
//
//        if ($dorm_data) $dorm_data = json_decode($dorm_data, true);
//        if ($bed_data) $bed_data = json_decode($bed_data, true);
//
//        if (!isset($dorm_data['id']))
//            $this->error('参数错误, 请先选择要点评的寝室');
//
//        $dorm = \app\common\model\Dorm::alias('a')
//            ->where('a.id', $dorm_data['id'])
//            ->where('a.status', \app\common\model\Dorm::NORMAL)
//            ->field('a.id,a.garden_number,a.building_number,a.name,a.number,a.school_id')
//            ->find();
//
//        $ret['data']['bed_list'] = Bed::where('garden_number', $dorm['garden_number'])
//            ->where('building_number', $dorm['building_number'])
//            ->where('dorm_number', $dorm['number'])
//            ->where('status', Bed::ZAIYONG)
//            ->where('student_id', '>', 0)
//            ->field('id,num,number,student_id')
//            ->order('num', 'asc')
//            ->select();
//
//        if (!$dorm)
//            $this->error('您要点评的寝室不存在');
//
//        $dorm_detail = \app\common\model\Building::alias('building')
//            ->join('__GARDEN__ garden', 'garden.id = building.garden_id')
//            ->join('__SCHOOL__ school', 'school.id = garden.school_id')
//            ->where('school.id', $dorm['school_id'])
//            ->where('garden.number', $dorm['garden_number'])
//            ->where('building.number', $dorm['building_number'])
//            ->field('school.id school_id,school.name school_name,garden.id garden_id,garden.number garden_number,garden.name garden_name,building.id building_id,building.number building_number,building.name building_name')
//            ->find();
//
//        if (!$dorm_detail) {
//            $this->error('error');
//        }
//
//        // 新的数组 用于存放所有的行为id
//        $behavior_ids = [];
//
//        // 判断是否有寝室点评
//        if (isset($dorm_data['behavior_ids']) && $dorm_data['behavior_ids']) {
//            // behavior_ids 是否是数组 不是的话转成数组(必须是以,连接)
//            if (!is_array($dorm_data['behavior_ids']))
//                $dorm_data['behavior_ids'] = explode(',', $dorm_data['behavior_ids']);
//
//            // 存放进behavior_ids
//            $behavior_ids = $dorm_data['behavior_ids'];
//        } else {
//            $dorm_data['behavior_ids'] = [];
//        }
//
//        // 新的数组 用于存放床位列表
//        $bed_list = [];
//        if ($bed_data) {
//
//            foreach ($bed_data as $key => $value) {
//                // 判断是否有床位点评
//                if (isset($value['behavior_ids']) && $value['behavior_ids']) {
//                    // behavior_ids 是否是数组 不是的话转成数组(必须是以,连接)
//                    if (!is_array($value['behavior_ids'])) {
//                        $bed_data[$key]['behavior_ids'] = explode(',', $value['behavior_ids']);
//                    }
//
//                    // 把点评床位的behavior_ids 追加进$behavior_ids
//                    $behavior_ids = array_merge($behavior_ids, $bed_data[$key]['behavior_ids']);
//                } else {
//                    $bed_data[$key]['behavior_ids'] = [];
//                }
//            }
//
//            // 重新组合床位信息 便于下面能快速的找到指定的床位
//            foreach ($ret['data']['bed_list'] as $key => $value) {
//                $bed_list[$value['id']] = $value;
//            }
//        }
//
//        // 获取并重新组合行为信息 便于下面能快速的找到指定的行为
//        $behavior_list = [];
//        if ($behavior_ids) {
//            $behavior_ids = array_unique($behavior_ids);
//            $behavior_list = \app\common\model\Behavior::alias('behavior')
//                ->join('__BEHAVIOR_CATEGORY__ category', 'category.id = behavior.category_id')
//                ->join('__BEHAVIOR_IMAGE__ image', 'image.id = behavior.image_id', 'left')
//                ->whereIn('behavior.id', $behavior_ids)
//                ->whereIn('category.type', [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT])
//                ->column('behavior.*,category.id behavior_category_id,category.type behavior_category_type,category.is_deduct,image.url image_url');
//        }
//
//        // 当前登录用户
//        $record_user_id = $this->auth->id;
//        $record_user_nickname = $this->auth->nickname;
//        $record_user_group = $this->auth->group_name;
//
//        Db::startTrans();
//        try {
//
//            $record = new BehaviorRecord();
//            $image = new BehaviorRecordImage();
//            $detail = new BehaviorRecordDetail();
//
//            $insert_detail_data = [];
//            $insert_image_data = [];
//
//            // 点评寝室
//            if ($dorm_data && $dorm_data['behavior_ids']) {
//                // 添加点评宿舍 record
//                $record->data([
//                    'record_user_id' => $record_user_id,
//                    'record_username' => $record_user_nickname,
//                    'record_user_group' => $record_user_group,
//                    'behavior_category_type' => BehaviorCategory::DORM,
//                    'school_id' => $dorm['school_id'],
//                    'dorm_id' => $dorm['id'],
//                    'comment' => isset($dorm_data['comment']) ? $dorm_data['comment'] : '',
//                    'json_data' => json_encode([
//                        'school_id' => $dorm_detail['school_id'],
//                        'school_name' => $dorm_detail['school_name'],
//                        'garden_id' => $dorm_detail['garden_id'],
//                        'garden_number' => $dorm_detail['garden_number'],
//                        'garden_name' => $dorm_detail['garden_name'],
//                        'building_id' => $dorm_detail['building_id'],
//                        'building_number' => $dorm_detail['building_number'],
//                        'building_name' => $dorm_detail['building_name'],
//                        'dorm_id' => $dorm['id'],
//                        'dorm_number' => $dorm['number'],
//                        'dorm_name' => $dorm['name'],
//                    ])
//                ]);
//                $record->save();
//                $record_id = $record->id;
//                // 添加点评宿舍 detail
//                foreach ($dorm_data['behavior_ids'] as $key => $value) {
//                    // 查找行为
//                    if (isset($behavior_list[$value]) && BehaviorCategory::DORM == $behavior_list[$value]['behavior_category_type']) {
//                        $score = $behavior_list[$value]['type'] == \app\common\model\Behavior::POSITIVE ? $behavior_list[$value]['score'] : $behavior_list[$value]['score'] * (-1);
//                        $insert_detail_data[] = [
//                            'record_id' => $record_id,
//                            'behavior_category_id' => $behavior_list[$value]['behavior_category_id'],
//                            'behavior_category_type' => $behavior_list[$value]['behavior_category_type'],
//                            'behavior_id' => $behavior_list[$value]['id'],
//                            'behavior_name' => $behavior_list[$value]['name'],
//                            'behavior_type' => $behavior_list[$value]['type'],
//                            'behavior_image_id' => $behavior_list[$value]['image_id'],
//                            'behavior_image_url' => $behavior_list[$value]['image_url'],
//                            'unit_score' => $score,
//                            'count' => 1,
//                            'score' => $score,
//                        ];
//                    }
//                }
//                // 添加点评宿舍 image
//                if (isset($dorm_data['images']) && $dorm_data['images']) {
//                    $images = explode(',', $dorm_data['images']);
//                    foreach ($images as $key => $value) {
//                        $insert_image_data[] = [
//                            'record_id' => $record_id,
//                            'url' => $value,
//                        ];
//                    }
//                }
//            }
//
//            // 点评床位(学生)
//            if ($bed_data) {
//                foreach ($bed_data as $k => $v) {
//                    // 查找床位
//                    if (isset($bed_list[$v['id']])) {
//                        if ($v['behavior_ids']) {
//                            // 添加点评床位 record
//                            $record->data([
//                                'record_user_id' => $record_user_id,
//                                'record_username' => $record_user_nickname,
//                                'record_user_group' => $record_user_group,
//                                'behavior_category_type' => BehaviorCategory::DORM_STUDENT,
//                                'school_id' => $dorm['school_id'],
//                                'dorm_id' => $dorm['id'],
//                                'bed_id' => $v['id'],
//                                'student_id' => $bed_list[$v['id']]['student_id'],
//                                'comment' => isset($dorm_data['comment']) ? $dorm_data['comment'] : '',
//                                'json_data' => json_encode([
//                                    'school_id' => $dorm_detail['school_id'],
//                                    'school_name' => $dorm_detail['school_name'],
//                                    'garden_id' => $dorm_detail['garden_id'],
//                                    'garden_number' => $dorm_detail['garden_number'],
//                                    'garden_name' => $dorm_detail['garden_name'],
//                                    'building_id' => $dorm_detail['building_id'],
//                                    'building_number' => $dorm_detail['building_number'],
//                                    'building_name' => $dorm_detail['building_name'],
//                                    'dorm_id' => $dorm['id'],
//                                    'dorm_number' => $dorm['number'],
//                                    'dorm_name' => $dorm['name'],
//                                    'bed_id' => $v['id'],
//                                    'bed_number' => $bed_list[$v['id']]['number'],
//                                    'bed_num' => $bed_list[$v['id']]['num'],
//                                    'student_id' => $bed_list[$v['id']]['student_id'],
//                                ])
//                            ]);
//                            $record->isUpdate(false)->save();
//                            $record_id = $record->id;
//                            // 添加点评床位 detail
//                            foreach ($v['behavior_ids'] as $key => $value) {
//                                // 查找行为
//                                if (isset($behavior_list[$value]) && BehaviorCategory::DORM_STUDENT == $behavior_list[$value]['behavior_category_type']) {
//                                    $score = $behavior_list[$value]['type'] == \app\common\model\Behavior::POSITIVE ? $behavior_list[$value]['score'] : $behavior_list[$value]['score'] * (-1);
//                                    $insert_detail_data[] = [
//                                        'record_id' => $record_id,
//                                        'behavior_category_id' => $behavior_list[$value]['behavior_category_id'],
//                                        'behavior_category_type' => $behavior_list[$value]['behavior_category_type'],
//                                        'behavior_id' => $behavior_list[$value]['id'],
//                                        'behavior_name' => $behavior_list[$value]['name'],
//                                        'behavior_type' => $behavior_list[$value]['type'],
//                                        'behavior_image_id' => $behavior_list[$value]['image_id'],
//                                        'behavior_image_url' => $behavior_list[$value]['image_url'],
//                                        'unit_score' => $score,
//                                        'count' => 1,
//                                        'score' => $score,
//                                    ];
//                                }
//                            }
//                            // 添加点评床位 image
//                            if (isset($v['images']) && $v['images']) {
//                                $images = explode(',', $v['images']);
//                                foreach ($images as $key => $value) {
//                                    $insert_image_data[] = [
//                                        'record_id' => $record_id,
//                                        'url' => $value,
//                                    ];
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//
//            // 批量保存
//            if ($insert_detail_data) {
//                $detail->saveAll($insert_detail_data);
//            }
//            if ($insert_image_data) {
//                $image->saveAll($insert_image_data);
//            }
//
//            // 提交事务
//            Db::commit();
//
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//
//            $this->error($e->getMessage() ? $e->getMessage() : '失败');
//        }
//
//        $this->success('成功');
//
//    }

    /**
     * @ApiTitle    (评价记录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/1/18)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/behaviorRecords)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="学生 id", sample="")
     * @ApiParams   (name="time_type", type="int|string", required=true, description="时间刷选类型 默认本月", sample="")
     * @ApiParams   (name="page", type="int", required=false, description="页码", sample="")
     * @ApiParams   (name="listRows", type="int", required=false, description="每页条数", sample="")
     * @ApiParams   (name="time_type", type="string|int", required=true, description="1|today=今天 2|yesterday=昨天 3|week=本周 4|lastweek=上周 5|day7=近7天 6|month=本月 7|lastmonth=上月 8|day30=近30天 9|quarter=本季度 10|lastquarter=上季度 11|year=本年 12|lastyear=上年 13|month1=近一个月 14|month3=近三个月", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function behaviorRecords()
    {
        $id = $this->request->request('id');
        $page = $this->request->request('page', 1);
        $listRows = $this->request->request('listRows');
        $time_type = $this->request->request('time_type');

        if (1 == $page) {
            $charts = BehaviorRecord::getCharts(BehaviorCategory::DORM, $id, $time_type, false);
            if (isset($charts['error'])) {
                $this->error($charts['msg']);
            }
        }

        $list = BehaviorRecord::getRecords(BehaviorCategory::DORM, $id, [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT], $time_type, $listRows);

        if (isset($list['error'])) {
            $this->error($list['msg']);
        }

        $this->success('', compact('charts', 'list'));
    }
}
